let bg = chrome.extension.getBackgroundPage();


function check() {
    let files = document.getElementById('file').files;
    for (let i = 0; i < files.length; i++) {
        let reader = new FileReader();
        reader.readAsText(files[i], 'utf-8');
        reader.onload = function () {
            let result = reader.result;
            let splits = result.split("\n");
            let data = null;
            splits.forEach(s => {
                if (s.trim().startsWith("#")) {
                    //没有JS的情况下
                    if (data != null) {
                        bg.saveWebsite(data.id, data.name, data.url, data.code);
                        data = null;
                    }
                    let array = s.trim().replace(/#/g, "")
                        .trim().split(/\s+/);
                    data = {id: array[0], name: array[1], url: array[2]};
                } else if (s.trim().startsWith("```js")) {
                    data.code = "";
                    data.startAppendCode = true;
                    return;
                } else if (s.trim().startsWith("```")) {
                    if (data != null) {
                        bg.saveWebsite(data.id, data.name, data.url, data.code);
                        data = null;
                    }
                }
                if (data && data.startAppendCode) {
                    data.code = data.code + "\n" + s;
                }
            });

        }
    }
}


function createUrl(url, id) {
    chrome.tabs.create({url}, function (tabs) {
        bg.addChargeTab(tabs.id,id);
        // if (code) {
        //     chrome.tabs.executeScript(tab2.id, {code});
        // }
    });
}


function appendTag(data) {
    let spanElement = document.createElement("span");
    spanElement.setAttribute('class', 'tag');
    spanElement.innerText = data.name;
    spanElement.id = "web-" + data.id;
    spanElement.onclick = () => {
        createUrl(data.url, data.id);
    }
    document.getElementById("content")
        .append(spanElement);
}

window.onload = () => {
    document.getElementById("upload").onclick = check;
    bg.searchByName((data) => {
        data.forEach(item => {
            appendTag(item);
        });
    });
}

//


//createUrl('https://www.baidu.com/s?ie=utf-8&wd=1',"alert(1)");
